# utils/audio_utils.py

import wave
import pyaudio


def pcm_to_wav(pcm_path, wav_path, channels=1, sampwidth=2, framerate=16000):
    """将PCM音频转换为WAV格式"""
    with open(pcm_path, 'rb') as pcmfile:
        pcmdata = pcmfile.read()
    with wave.open(wav_path, 'wb') as wavfile:
        wavfile.setnchannels(channels)
        wavfile.setsampwidth(sampwidth)
        wavfile.setframerate(framerate)
        wavfile.writeframes(pcmdata)


def play_wav(wav_path):
    """播放WAV音频文件"""
    chunk = 1024
    wf = wave.open(wav_path, 'rb')
    p = pyaudio.PyAudio()
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                    channels=wf.getnchannels(),
                    rate=wf.getframerate(),
                    output=True)
    data = wf.readframes(chunk)
    while data:
        stream.write(data)
        data = wf.readframes(chunk)
    stream.stop_stream()
    stream.close()
    p.terminate()
